<script setup lang="ts">
import { reactive, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import router from '@/router'
import { useUserStore } from '@/stores/user'
import {
  userGetTopicDraftService,
  userPublishTopicService,
  userSaveTopicDraftService
} from '@/api/user'
import {
  adminGetTopicDraftService,
  adminPublishTopicService,
  adminSaveTopicDraftService
} from '@/api/admin'

const topic = ref({
  title: '',
  content: '',
  image: '', // 用于存储上传后返回的图片地址
  createTime: '',
  updateTime: ''
})

const topicForm = ref()

// 进入界面就请求草稿
const getTopicDraft = async () => {
  // 发起请求获取草稿
  const res = await adminGetTopicDraftService()
  console.log(res.data.data)
  topic.value = res.data.data
}

getTopicDraft()

// 上传成功后处理
const handleAvatarSuccess = (response: any) => {
  if (response.code === 1) {
    topic.value.image = response.data // 假设后端返回图片路径在 data 字段
    console.log(response.data)
    ElMessage.success('图片上传成功！')
  } else {
    ElMessage.error('图片上传失败，请重试！')
  }
}

// 上传前校验
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 5
  if (!isImage) {
    ElMessage.error('只能上传图片格式文件！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 5MB！')
    return false
  }
  return true
}

// 保存并退出
const saveAndExit = () => {
  ElMessage.success('保存成功！')
  adminSaveTopicDraftService(topic.value)
  router.push('/teacher/topic')
}

// 请求头
const userStore = useUserStore()
const uploadHeaders = ref({
  authentication: `${userStore.token}` // 假设 userStore.token 存储的是有效的 Token
})

const rule = reactive({
  title: [
    {
      required: true,
      message: '请输入标题',
      trigger: 'blur'
    }
  ]
})

const publish = async () => {
  const valid = await topicForm.value.validate()
  if (!valid) {
    ElMessage.error('请填写完整信息！')
    return
  }
  // 发起请求发布话题
  await adminPublishTopicService(topic.value)
  ElMessage.success('发布成功！')
  await router.push('/teacher/topic')
}


</script>

<template>
  <div id="main-topicCreatePage">
    <h1>话题发布</h1>
    <el-form style="margin-top: 10px" :model="topic" :rules="rule" ref="topicForm">
      <el-form-item prop="title">
        <el-input
          style="height: 50px; width: 50%"
          placeholder="请输入标题(必须)"
          v-model="topic.title"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          type="textarea"
          :autosize="{ minRows: 5, maxRows: 10 }"
          placeholder="请输入话题内容(可选)"
          v-model="topic.content"
        ></el-input>
      </el-form-item>
    </el-form>
    <div style="display: flex; align-items: end">
      <el-upload
        class="avatar-uploader"
        action="http://localhost:8000/teacher/common/upload"
        :headers="uploadHeaders"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        name="file"
      >
        <img v-if="topic.image" :src="topic.image" class="avatar" alt="上传的图片" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>
      <el-button style="margin-left: 5px" v-if="topic.image" type="danger" @click="topic.image = ''"
        >清空图片
      </el-button>
    </div>
    <div
      style="display: flex; align-items: center; margin-top: 20px; justify-content: space-between"
    >
      <div>
        <el-button type="primary" @click="publish">发布</el-button>
        <el-button type="warning" @click="saveAndExit">保存并退出</el-button>
      </div>
      <div v-if="topic.updateTime || topic.createTime">
        上次编辑于：{{ topic.updateTime ? topic.updateTime : topic.createTime }}
      </div>
    </div>
  </div>
</template>

<style scoped>
#main-topicCreatePage {
  position: relative;
  padding: 10px;
  margin: 20px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
}

.avatar-uploader {
  width: auto; /* 固定宽度 */
  height: auto; /* 高度根据宽度自动调整 */
  overflow: hidden;
  border-radius: 5px;
}

.avatar-uploader .avatar {
  width: auto;
  height: 178px;
  display: block;
  transition: all 0.3s;
}
</style>
